<?php

require_once '../vendor/autoload.php';

class Router
{
    public static function updateRouter()
    {
        $routerConfig = include_once '../config/router.php';

        $router = [];

        // 处理字符串类型的路由配置
        if (!empty($routerConfig['path'])) {
            $router = array_merge($router, self::processPathRouter($routerConfig['path']));
        }

        // 处理字符串类型的路由配置
        if (!empty($routerConfig['namespace'])) {
            $router = array_merge($router, self::processNamespaceRouter($routerConfig['namespace']));
        }

        self::saveRouterToFile($router);
    }

    /**
     * 处理命名空间类型的路由配置
     */
    private static function processPathRouter($pathRouter = [])
    {
        if (empty($pathRouter)) {
            return [];
        }

        $router = [];
        foreach ($pathRouter as $kRouter => $vRouter) {
            $router[strtolower($vRouter[0])] = $vRouter;
        }

        return $router;
    }

    /**
     * 处理命名空间类型的路由配置
     */
    private static function processNamespaceRouter($nsRouter = [])
    {
        if (empty($nsRouter)) {
            return [];
        }

        $router = [];
        foreach ($nsRouter as $kNs => $vNs) {
            foreach ($vNs as $kRouter => $vRouter) {
                list($empty, $app, $moduleName) = explode('\\', $kNs);
                if ($vRouter[0] == '*') {
                    // 如果是通配符，就反射获取类下面的public方法，统统放到路由表中
                    $reflection = new ReflectionClass($kNs . '\\' . $kRouter);
                    $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);
                    foreach ($methods as $kName => $vName) {
                        $router[strtolower('/' . $moduleName . '/' . $kRouter . '/' . $vName->name)] = ['/' . $moduleName . '/' . $kRouter . '/' . strtolower($vName->name), $kNs . '\\' . $kRouter . '\\' . strtolower($vName->name), '*'];
                    }
                } else {
                    foreach ($vRouter as $kName => $vName) {
                        $router[strtolower('/' . $moduleName . '/' . $kRouter . '/' . $vName[0])] = ['/' . $moduleName . '/' . $kRouter . '/' . strtolower($vName[0]), $kNs . '\\' . $kRouter . '\\' . strtolower($vName[0]), $vName[1]];
                    }
                }
            }
        }

        return $router;
    }

    /**
     * 将路由数组写入文件
     */
    private static function saveRouterToFile($routerArr)
    {
        $routerFile = '../runtime/router/router.json';
        if (!file_exists('../runtime/router/')) {
            $mkRes = mkdir('../runtime/router/', 0777, true);
            if (!$mkRes) {
                return '没有相对应的文件夹，并且创建失败';
            }
        }

        $fd = fopen($routerFile, 'w');
        fwrite($fd, json_encode($routerArr));
        fclose($fd);
    }
}

if (file_exists('../config/router.php')) {
    Router::updateRouter();
} else {
    echo '../config/router.php not exist';
}
